// src/components/common/loading/LoadingContext.tsx
import React, { createContext, useContext, useState, ReactNode, useCallback } from 'react';
import { Spin } from '@arco-design/web-react';
import styles from './loadingText.module.scss';

// 创建Context并设置默认值
const LoadingContext =
  createContext({
    loading: false,
    tip: '加载中...',
    showLoading: () => {},
    hideLoading: () => {},
  });

// 自定义Hook，方便组件使用loading功能
export const useLoading = () => {
  const context = useContext(LoadingContext);
  if (!context) {
    throw new Error('useLoading must be used within a LoadingProvider');
  }
  return context;
};

// LoadingProvider组件，包裹整个应用
export const LoadingProvider = ({ children }) => {
  const [loading, setLoading] = useState(false);
  const [tip, setTip] = useState('加载中...');

  // 显示loading的方法
  const showLoading = useCallback((customTip) => {
    setTip(customTip || '加载中...');
    setLoading(true);
  }, []);

  // 隐藏loading的方法
  const hideLoading = useCallback(() => {
    setLoading(false);
  }, []);

  const value = {
    loading,
    tip,
    showLoading,
    hideLoading,
  };

  return (
    <LoadingContext.Provider value={value}>
      {children}
      {/* 全局loading组件，固定定位在页面中央 */}
      {loading && (
        <div className={styles.globalLoadingMask}>
          <Spin tip={tip} size="large" dot />
        </div>
      )}
    </LoadingContext.Provider>
  );
};

// 导出Context（不常用，推荐使用useLoading Hook）
export default LoadingContext;
